//
//  UserCouponView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/1.
//

import UIKit
import MJRefresh

class UserCouponView: UIView {
    var emptyView: LYEmptyView!
    var tableView: BaseTableView!
    var dataArray: [CouponDataModel] = [] //有效券
    var expiredArray: [CouponDataModel] = [] //过期的优惠券
    var showExpireFlag: Bool = false
    var footerView: UIView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: frame.size.height), style: .grouped)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.register(UserRewardCell.self, forCellReuseIdentifier: "UserRewardCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = Theme.whiteColor
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 82
        self.addSubview(tableView)
        self.createBottomView()
        self.setUpNoData()
        self.addPullRefreash()
        self.fetchGetExpiredCouponList(status: "1,2")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.tableView.frame = self.bounds
        self.footerView.frame = CGRect.init(x: 0, y: self.frame.size.height - TabbarHeight, width: kScreenWidth, height: TabbarHeight)
    }
    
    ///底部过期按钮
    func createBottomView(){
        footerView = UIView.init(frame: CGRect.init(x: 0, y: self.frame.size.height - TabbarHeight, width: kScreenWidth, height: TabbarHeight))
        footerView.backgroundColor = UIColor.white
        footerView.clipsToBounds = true

        let btn = UIButton()
        btn.setup_titleLabel(text: MMLocalizedString("view_invalid_coupons", comment: "查看已过期的券"))
        btn.setup_titleColor(color: Theme.titleLabColor)
        btn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        btn.setup_image(image: UIImage.init(named: "icon_filter_down"))
        btn.semanticContentAttribute = .forceRightToLeft
        btn.addTarget(self, action: #selector(expiredCouponAction), for: .touchUpInside)
        footerView.addSubview(btn)
        
        btn.snp.makeConstraints { make in
            make.height.equalTo(46)
            make.width.equalTo(kScreenWidth)
            make.left.equalTo(0)
            make.top.equalTo(0)
        }
        self.addSubview(footerView)
    }
    
    //MARK: - 下拉刷新
    func addPullRefreash()  {
        weak var weakself = self
        let headerR = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself!.fetchGetCouponLiset(status: "0")
            weakself!.showExpireFlag = false
            weakself!.footerView.isHidden = false
        })
        headerR?.activityIndicatorViewStyle = .gray
        self.tableView.mj_header = headerR
        self.tableView.mj_header?.beginRefreshing()
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        self.tableView.ly_emptyView = self.emptyView
    }
    
    ///空视图
    func willShowEmptyView() {
        if self.dataArray.count == 0 && self.expiredArray.count == 0 {
            self.tableView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("no_data", comment: "暂无数据")
        }else{
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    func changeCouponItem(){
        if self.dataArray.count > 0 {
            return
        }
        self.fetchGetCouponLiset(status: "0")
    }
    
    ///获取优惠券列表 0 未使用
    func fetchGetCouponLiset(status: String) {
        var param = NSMutableDictionary() as! [String: String]
        param["pageSize"] = "9999"
        param["pageNumber"] = "1"
        param["status"] = status //全部
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getCouponcodeDataNew(param: param), objectType: CouponListResModel.self) { data in
            self.tableView.mj_header?.endRefreshing()
            let resultObj = data as! CouponListResModel
            if resultObj.code == "1" {
                let tempArr = resultObj.data?.content ?? []
                //有效的券
                self.dataArray = tempArr
                self.tableView.reloadData()
            }else{
                self.viewController().view?.makeToast(message: resultObj.msg ?? "")
            }
            self.willShowEmptyView()
        } error: { err in
            self.tableView.mj_header?.endRefreshing()
            self.willShowEmptyView()
            self.viewController().view?.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///获取优惠券列表 1  已使用 2 已过期
    func fetchGetExpiredCouponList(status: String) {
        var param = NSMutableDictionary() as! [String: String]
        param["pageSize"] = "9999"
        param["pageNumber"] = "1"
        param["status"] = status
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getCouponcodeDataNew(param: param), objectType: CouponListResModel.self) { data in
            let resultObj = data as! CouponListResModel
            if resultObj.code == "1" {
                let tempArr = resultObj.data?.content ?? []
                //失效的券
                self.expiredArray = tempArr
            }
        } error: { err in
            print(err?.domain ?? "")
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///获取过期券和已使用的券
    @objc func expiredCouponAction(){
        if self.showExpireFlag == false {
            self.showExpireFlag = true
            self.footerView.isHidden = true
        }
        self.tableView.reloadData()
        
       
    }
}

extension UserCouponView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.dataArray.count
        }else{
            return self.showExpireFlag ? self.expiredArray.count : 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.01
        }
        return TabbarHeight
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserRewardCell", for: indexPath) as! UserRewardCell
        
        if indexPath.section == 0 {
            if self.dataArray.count > indexPath.row {
                let itemModel = self.dataArray[indexPath.row]
                cell.setUserRewardCell(data: itemModel)
            }
        }else{
            if self.expiredArray.count > indexPath.row {
                let itemModel = self.expiredArray[indexPath.row]
                cell.setUserRewardCell(data: itemModel)
            }
        }
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        return cell
    }
}
